<template>
  <view class="shop-details-container">
    <view class="header">
      <view class="back-btn" @tap="navigateBack">
        <text class="back-icon">←</text>
      </view>
      <text class="title">门店详情</text>
      <view class="header-right">
      </view>
    </view>

    <!-- 门店图片轮播 -->
    <view class="image-carousel">
      <swiper class="swiper" :indicator-dots="true" :autoplay="true" :interval="5000" :duration="1000" @change="onSwiperChange">
        <swiper-item v-for="(item, index) in imageList" :key="index">
          <image class="shop-main-image" :src="item.url" mode="aspectFill"></image>
        </swiper-item>
      </swiper>
      <view class="image-indicator">
        <text class="indicator-text">{{ currentImageIndex + 1 }}/{{ imageList.length }}</text>
      </view>
    </view>

    <!-- 门店基本信息 -->
    <!-- 加载提示 -->
    <view v-if="loading" class="loading-container">
      <view class="loading-spinner"></view>
      <text class="loading-text">加载中...</text>
    </view>
    
    <!-- 错误提示 -->
    <view v-else-if="errorMsg" class="error-container">
      <text class="error-text">{{ errorMsg }}</text>
      <button class="retry-button" @click="onRetry">重试</button>
    </view>
    
    <!-- 门店基本信息 -->
    <view v-else class="shop-info-section">
      <text class="shop-name">{{ shopInfo.name }}</text>
      <view class="rating-reviews">
        <view class="rating">
          <text class="star">★★★★★</text>
          <text class="score">{{ shopInfo.score }}</text>
        </view>
        <text class="reviews-count">评论：{{ shopInfo.reviewsCount }}</text>
      </view>
      <view class="business-info">
        <text class="business-label">营业时间：</text>
        <text class="business-value">{{ shopInfo.businessHours }}</text>
      </view>
      <view class="address-info">
        <text class="address-label">地址：</text>
        <text class="address-value">{{ shopInfo.address }}</text>
      </view>
    </view>

    <!-- 服务项目 -->
    <view class="service-section">
      <view class="section-title">
        <text class="title-text">服务项目</text>
      </view>
      <view class="service-item" v-for="(service, index) in serviceItems" :key="index">
        <view class="service-info">
          <text class="service-name">{{ service.name }}</text>
          <text class="service-desc">{{ service.description }}</text>
        </view>
        <view class="service-price">¥ {{ service.price }}</view>
      </view>
    </view>

    <!-- 服务评价 -->
    <view class="reviews-section">
      <view class="section-title">
        <text class="title-text">服务评价</text>
      </view>
      <view v-if="reviewsList.length > 0">
        <view class="review-item" v-for="(review, index) in reviewsList" :key="review.id || index">
          <view class="review-header">
            <view class="reviewer-info">
              <view class="reviewer-avatar">
                <text class="avatar-text">{{ review.avatarText }}</text>
              </view>
              <view class="reviewer-details">
                <text class="reviewer-name">{{ review.nickName }}</text>
                <text class="review-date">{{ review.createTime }}</text>
              </view>
            </view>
            <view class="review-rating">
              <text class="star">{{ this.getStarRating(review.rate) }}</text>
            </view>
          </view>
          <view class="review-content">
            <text class="content-text">{{ review.content }}</text>
          </view>
        </view>
      </view>
      <view v-else class="no-reviews">
        <text class="no-reviews-text">暂无评价</text>
      </view>
    </view>

    <!-- 底部预约按钮 -->
    <view class="bottom-book-bar">
      <button class="book-button" @click="confirmBooking">立即预约</button>
    </view>
  </view>
</template>

<script>
export default {
  name: 'ShopDetails',
  data() {
      return {
        shopInfo: {
          id: '1',
          name: '伟业汽车维修厂(人民路店)',
          score: 3,
          reviewsCount: 322,
          businessHours: '周一至周五 09:00-22:00',
          address: '山阳区人民路中路32号',
          phone: '18893029302',
          imageUrl: '../../static/car-repair-shop.png'
        },
        // 轮播图相关数据
        imageList: [], // 存储门店图片列表
        currentImageIndex: 0, // 当前显示的图片索引
        // 加载和错误状态
        loading: false, // 加载状态
        errorMsg: '', // 错误信息
        serviceItems: [
          { name: '工时费', description: '(每小时)', price: 199 },
          { name: '轮胎', description: '', price: 399 },
          { name: '机油', description: '', price: 299 },
          { name: '机滤', description: '', price: 89 }
        ],
        // 服务评价列表
        reviewsList: []
      }
    },
  onLoad(options) {
    // 如果有门店ID，获取门店详情和图片列表
    if (options.id) {
      console.log('获取门店ID:', options.id)
      // 设置当前门店ID
      this.shopInfo.id = options.id
      // 获取门店详情数据
      this.fetchShopDetails(options.id)
      // 获取门店图片列表
      this.fetchImageList(options.id)
    } else {
      // 如果没有ID，使用默认ID
      this.fetchShopDetails(this.shopInfo.id)
      this.fetchImageList(this.shopInfo.id)
    }
  },
  methods: {
    navigateBack() {
      uni.navigateBack()
    },
    confirmBooking() {
      // 跳转到预约表单页面
      uni.navigateTo({
        url: '/pages/booking-form/booking-form?shopId=' + this.shopInfo.id
      })
    },
    // 获取门店详情数据
    fetchShopDetails(id) {
      // 设置加载状态
      this.loading = true;
      this.errorMsg = '';
      
      uni.request({
        url: `http://localhost:8080/cc/merchant/list?id=${id}`,
        method: 'GET',
        success: (res) => {
          if (res.statusCode === 200 && res.data && res.data.code === 200) {
            // 确保data是数组且有元素
            if (Array.isArray(res.data.data) && res.data.data.length > 0) {
              const shopData = res.data.data[0];
              // 完整映射接口返回的数据到shopInfo
              this.shopInfo = {
                id: shopData.id || '',
                name: shopData.name || '未知门店',
                score: shopData.rate || 0, // 使用rate字段作为评分
                reviewsCount: 0, // 初始化评论数为0
                // 处理营业时间，从startTime和endTime字段组合
                businessHours: shopData.startTime && shopData.endTime 
                  ? `${this.formatTime(shopData.startTime)}-${this.formatTime(shopData.endTime)}`
                  : '营业时间待定',
                address: shopData.address || '地址信息未提供',
                phone: shopData.phone || '',
                imageUrl: '../../static/car-repair-shop.png'
              };
              console.log('门店详情数据获取成功:', this.shopInfo);
              
              // 获取门店评论数
            this.fetchEvaluateCount(id);
            // 获取门店服务列表
            this.fetchServiceList(id);
            // 获取服务评价列表
            this.fetchEvaluateList(id);
            } else {
              console.error('未找到门店信息');
              this.errorMsg = '未找到门店信息';
            }
          } else {
            const errorMessage = res.data?.msg || '获取门店详情失败';
            console.error('获取门店详情失败:', errorMessage);
            this.errorMsg = errorMessage;
          }
        },
        fail: (err) => {
          console.error('请求门店详情失败:', err);
          this.errorMsg = '网络错误，请稍后重试';
        },
        complete: () => {
          // 无论成功失败，都结束加载状态
          this.loading = false;
        }
      });
    },
    // 重试获取门店信息
    onRetry() {
      this.fetchShopDetails(this.shopInfo.id);
    },
    // 获取门店评论数
    fetchEvaluateCount(merchantId) {
      uni.request({
        url: `http://localhost:8080/cc/merchant/evaluateCount`,
        method: 'GET',
        data: {
          merchantId: merchantId
        },
        success: (res) => {
          if (res.statusCode === 200 && res.data && res.data.code === 200) {
            // 更新评论数
            this.shopInfo.reviewsCount = res.data.data || 0;
            console.log('门店评论数获取成功:', this.shopInfo.reviewsCount);
          } else {
            console.error('获取门店评论数失败:', res.data?.msg || '未知错误');
          }
        },
        fail: (err) => {
          console.error('请求门店评论数失败:', err);
        }
      });
    },
    // 获取门店服务列表
    fetchServiceList(mId) {
      uni.request({
        url: `http://localhost:8080/cc/merchant/serviceDetailsList`,
        method: 'GET',
        data: {
          mId: mId
        },
        success: (res) => {
          if (res.statusCode === 200 && res.data && res.data.code === 200) {
            // 处理返回的服务列表数据
            if (Array.isArray(res.data.data)) {
              this.serviceItems = res.data.data.map(service => ({
                id: service.id || '',
                name: service.name || '',
                description: '', // 接口未返回描述信息
                price: parseFloat(service.originalPrice) || 0
              }));
              console.log('服务列表获取成功:', this.serviceItems);
            } else {
              console.error('服务列表数据格式错误');
              this.serviceItems = [];
            }
          } else {
            console.error('获取服务列表失败:', res.data?.msg || '未知错误');
          }
        },
        fail: (err) => {
          console.error('请求服务列表失败:', err);
        }
      });
    },
    // 获取服务评价列表
    fetchEvaluateList(merchantId) {
      uni.request({
        url: `http://localhost:8080/cc/merchant/evaluateList`,
        method: 'GET',
        data: {
          merchantId: merchantId
        },
        success: (res) => {
          if (res.statusCode === 200 && res.data && res.data.code === 200) {
            // 处理返回的评价列表数据
            if (Array.isArray(res.data.data)) {
              this.reviewsList = res.data.data.map(review => ({
                id: review.id || '',
                content: review.content || '',
                rate: review.rate || 5,
                createTime: this.formatReviewDate(review.createTime),
                nickName: review.nickName || '',
                avatarText: this.getAvatarText(review.nickName || '')
              }));
              console.log('服务评价列表获取成功:', this.reviewsList);
            } else {
              console.error('服务评价列表数据格式错误');
              this.reviewsList = [];
            }
          } else {
            console.error('获取服务评价列表失败:', res.data?.msg || '未知错误');
          }
        },
        fail: (err) => {
          console.error('请求服务评价列表失败:', err);
        }
      });
    },
    // 获取用户头像文字（取nickName的第一个字）
    getAvatarText(nickName) {
      if (!nickName) return '用';
      return nickName.charAt(0);
    },
    // 格式化评价日期
    formatReviewDate(dateStr) {
      if (!dateStr) return '';
      try {
        const date = new Date(dateStr);
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');
        return `${year}-${month}-${day}`;
      } catch (error) {
        console.error('日期格式化错误:', error);
        return '';
      }
    },
    // 生成星级评分显示
    getStarRating(rate) {
      const starCount = Math.max(0, Math.min(5, parseInt(rate) || 0));
      return '★'.repeat(starCount);
    },
    // 获取门店图片列表
    fetchImageList(mid) {
      uni.request({
        url: `http://localhost:8080/cc/merchant/imgList?mid=${mid}`,
        method: 'GET',
        success: (res) => {
          if (res.statusCode === 200 && res.data && res.data.code === 200) {
            // 适配数据结构，将img字段转换为url字段
            this.imageList = (res.data.data || []).map(item => ({
              url: item.img || this.shopInfo.imageUrl
            }))
            // 如果没有图片，使用默认图片
            if (this.imageList.length === 0) {
              this.imageList = [{ url: this.shopInfo.imageUrl }]
            }
          } else {
            console.error('获取门店图片列表失败:', res.data)
            // 失败时使用默认图片
            this.imageList = [{ url: this.shopInfo.imageUrl }]
          }
        },
        fail: (err) => {
          console.error('请求门店图片列表失败:', err)
          // 请求失败时使用默认图片
          this.imageList = [{ url: this.shopInfo.imageUrl }]
        }
      })
    },
    // 轮播图切换时更新当前索引
    onSwiperChange(e) {
      this.currentImageIndex = e.detail.current
    },
    // 格式化时间，去除可能的毫秒部分
    formatTime(timeStr) {
      if (!timeStr) return '';
      // 如果时间字符串包含毫秒部分，去除它
      if (timeStr.includes('.')) {
        return timeStr.split('.')[0];
      }
      return timeStr;
    }
  }
}
</script>

<style lang="scss" scoped>
.shop-details-container {
  background-color: #f8f8f8;
  min-height: 100vh;
  padding-bottom: 120rpx; // 为底部按钮留出空间
}

.header {
  padding: 60rpx 0 30rpx 0;
  text-align: center;
  background-color: #fff;
  position: sticky;
  top: 0;
  z-index: 10;
  display: flex;
  align-items: center;
  justify-content: space-between;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
}

.back-btn {
  position: absolute;
  left: 30rpx;
  top: 50%;
  transform: translateY(-50%);
  padding: 10rpx;
  margin-top: 10px;
}

.back-icon {
  font-size: 40rpx;
  font-weight: bold;
}

.title {
  font-size: 36rpx;
  font-weight: bold;
  margin: auto;
}

.header-right {
  position: absolute;
  right: 30rpx;
  top: 50%;
  transform: translateY(-50%);
  padding: 10rpx;
}

.more-icon {
  font-size: 32rpx;
}

/* 门店图片轮播 */
.image-carousel {
  margin-top: 20rpx; /* 调整上边距，使页面内容不被挡住 */
  height: 400rpx;
  position: relative;
  overflow: hidden;
}

.swiper {
  width: 100%;
  height: 100%;
}

.shop-main-image {
  width: 100%;
  height: 100%;
  display: block; /* 确保图片作为块级元素显示 */
  mode: aspectFill; /* 保持宽高比并填充整个区域 */
}

.image-indicator {
  position: absolute;
  bottom: 20rpx;
  right: 20rpx;
  background-color: rgba(0, 0, 0, 0.6);
  padding: 8rpx 16rpx;
  border-radius: 15rpx;
}

.indicator-text {
  color: #fff;
  font-size: 24rpx;
}

/* 门店基本信息 */
.shop-info-section {
  background-color: #fff;
  padding: 30rpx;
  margin-bottom: 20rpx;
}

.shop-name {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
  display: block;
  margin-bottom: 15rpx;
}

.rating-reviews {
  display: flex;
  align-items: center;
  margin-bottom: 15rpx;
}

.rating {
  display: flex;
  align-items: center;
  margin-right: 20rpx;
}

.star {
  color: #ffc107;
  font-size: 24rpx;
  margin-right: 8rpx;
}

.score {
  color: #666;
  font-size: 24rpx;
  font-weight: bold;
}

.reviews-count {
  color: #999;
  font-size: 24rpx;
}

.business-info,
.address-info {
  margin-bottom: 10rpx;
  font-size: 26rpx;
}

.business-label,
.address-label {
  color: #999;
  margin-right: 10rpx;
}

.business-value,
.address-value {
  color: #666;
}

/* 服务项目 */
.service-section {
  background-color: #fff;
  margin-bottom: 20rpx;
}

.section-title {
  padding: 20rpx 30rpx;
  border-bottom: 1rpx solid #f0f0f0;
}

.title-text {
  font-size: 30rpx;
  font-weight: bold;
  color: #333;
}

.service-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 25rpx 30rpx;
  border-bottom: 1rpx solid #f0f0f0;
}

.service-info {
  flex: 1;
}

.service-name {
  font-size: 28rpx;
  color: #333;
  margin-bottom: 5rpx;
  display: block;
}

.service-desc {
  font-size: 24rpx;
  color: #999;
}

.service-price {
  font-size: 30rpx;
  font-weight: bold;
  color: #ff6700;
}

/* 服务评价 */
    .reviews-section {
      background-color: #fff;
      margin-bottom: 20rpx;
    }

    .review-item {
      padding: 25rpx 30rpx;
      border-bottom: 1rpx solid #f0f0f0;
    }
    
    .review-item:last-child {
      border-bottom: none;
    }
    
    /* 暂无评价样式 */
    .no-reviews {
      padding: 60rpx 30rpx;
      text-align: center;
    }
    
    .no-reviews-text {
      font-size: 28rpx;
      color: #999;
    }

.review-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15rpx;
}

.reviewer-info {
  display: flex;
  align-items: center;
}

.reviewer-avatar {
  width: 60rpx;
  height: 60rpx;
  border-radius: 50%;
  background-color: #1677ff;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 15rpx;
}

.avatar-text {
  color: #fff;
  font-size: 28rpx;
  font-weight: bold;
}

.reviewer-details {
  display: flex;
  flex-direction: column;
}

.reviewer-name {
  font-size: 26rpx;
  color: #333;
  margin-bottom: 2rpx;
}

.review-date {
  font-size: 22rpx;
  color: #999;
}

.review-content {
  margin-top: 10rpx;
}

.content-text {
  font-size: 26rpx;
  color: #666;
  line-height: 40rpx;
}

/* 底部预约按钮 */
.bottom-book-bar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: #fff;
  padding: 20rpx 30rpx;
  box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.1);
}

.book-button {
  width: 100%;
  height: 90rpx;
  line-height: 90rpx;
  background-color: #1677ff;
  color: #fff;
  border: none;
  border-radius: 8rpx;
  font-size: 32rpx;
}

/* 加载状态样式 */
.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60rpx 0;
}

.loading-spinner {
  width: 60rpx;
  height: 60rpx;
  border: 4rpx solid rgba(0, 0, 0, 0.1);
  border-radius: 50%;
  border-top-color: #1677ff;
  animation: spin 1s ease-in-out infinite;
  margin-bottom: 20rpx;
}

@keyframes spin {
  to { transform: rotate(360deg); }
}

.loading-text {
  font-size: 28rpx;
  color: #666;
}

/* 错误状态样式 */
.error-container {
  padding: 60rpx 30rpx;
  text-align: center;
}

.error-text {
  font-size: 28rpx;
  color: #ff4d4f;
  margin-bottom: 30rpx;
  display: block;
}

.retry-button {
  background-color: #1677ff;
  color: #fff;
  border: none;
  border-radius: 8rpx;
  padding: 15rpx 40rpx;
  font-size: 28rpx;
}
</style>